
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QRegularExpression>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //初始化状态栏，显示选中的文件数量
    countFileNumber.setText(QString("   选中文件数量:%1").arg(0));
    ui->statusbar->addWidget(&countFileNumber);

    //文件选择对话框，让用户选择文件，并将文件加入到QListWidget控件中去
    connect(ui->actionSelectFile,&QAction::triggered,this,&MainWindow::chooseFiles);

    connect(ui->applyPushButton,&QPushButton::clicked,this,&MainWindow::applyFileRename);

    //清空所有文件信息
    connect(ui->cleanPushButton,&QPushButton::clicked,this,&MainWindow::cleanAllFiles);
}

MainWindow::~MainWindow()
{
    delete ui;
}

//---------------------------------------------------成员 函数实现------------------------------------------------
int MainWindow::chooseFiles()
{
    filePathList = QFileDialog::getOpenFileNames(this,"选择一个或多个文件","C:\\Users\\TANG");
    for (int i = 0;i < filePathList.size();i++)
    {
        QFileInfo fileInfo(filePathList[i]);
        fileInfoList.push_back(fileInfo);
    }
    ui->pathListWidget->clear();
    for(int j=0;j<fileInfoList.size();j++)
    {
        ui->pathListWidget->addItem(fileInfoList[j].fileName());
        countFileNumber.setText(QString("   选中文件数量:%1").arg(ui->pathListWidget->count()));
    }
    return 0;
}


int MainWindow::applyFileRename()
{
    QString oldFileBaseName=" ";
    QString oldFileSuffix=" ";
    QString newFileBaseName=" ";
    QString newFileSuffix="";
    QString newFilePath=" ";
    for(int i=0;i<filePathList.size();i++)
    {
        QFile file(filePathList[i],this);
        qDebug()<<"文件名："<<file.fileName();

        newFilePath=filePathList[i];

        QFileInfo fileInfo(filePathList[i]);
        oldFileBaseName=fileInfo.baseName();
        oldFileSuffix=fileInfo.suffix();

        if("(空)"!=ui->newFileBaseName->text())
        {
            newFileBaseName=ui->newFileBaseName->text() + QString::number(i+1);
        }
        else
        {
            newFileBaseName=oldFileBaseName;
        }

        if("(空)"!=ui->newFileSuffix->text())
        {
            newFileSuffix=ui->newFileSuffix->text();
        }
        else
        {
            newFileSuffix=oldFileSuffix;
        }

        newFilePath.replace(oldFileBaseName,newFileBaseName);
        newFilePath.replace(oldFileSuffix,newFileSuffix);
        qDebug()<<"新的文件名："<<newFilePath;
        file.rename(newFilePath);
    }
    QMessageBox::information(this,"提示","已完成修改！");
    cleanAllFiles();
    return 0;
}


int MainWindow::cleanAllFiles()
{
    ui->pathListWidget->clear();
    fileInfoList.clear();
    countFileNumber.setText(QString("   选中文件数量:%1").arg(ui->pathListWidget->count()));
    return 0;
}




